package com.piece.admin.context.init;

import com.piece.admin.model.TbSysJob;
import com.piece.admin.service.TbSysJobService;
import com.piece.core.framework.util.schedule.ScheduleUtil;
import com.piece.core.mongo.entity.MongoMessage;
import com.piece.core.mongo.service.MongoMessageService;
import com.piece.core.web.initializer.SystemScript;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

/**
 * 加载定时器任务
 */
@Slf4j
@Component
public class InitTimeTask implements SystemScript {

    @Autowired
    private Scheduler scheduler;

    @Resource
    private TbSysJobService tbSysJobService;

    @Resource
    private MongoMessageService mongoMessageService;

    @Override
    public String getScriptName() {
        return "加载定时器任务";
    }

    @Override
    public void doInit() {
        // 加载定时器
        List<TbSysJob> jobs = tbSysJobService.findByRunJobs();

        jobs.forEach(job -> {
            ScheduleUtil.createScheduleJob(scheduler, tbSysJobService.transToScheduleJob(job));
        });

        // 加载通知处理器
        List<MongoMessage> messages = mongoMessageService.findNoticesWithOverdueTime(null);
        messages.stream().forEach(message -> {
            mongoMessageService.dealOverdueMessage(message);
        });
    }

    @Override
    public Integer getIndex() {
        return Integer.MAX_VALUE;
    }
}
